﻿namespace BathroomLocator.Services.Serializers
{
	using System;
	using System.Collections.Specialized;
	using System.Web;
	using BathroomLocator.Services.Infrastructure;

	public class FormatSerializerFactory : IFormatSerializerFactory
	{
		private IFormatSerializer jsonSerializer;
		private IFormatSerializer jsonpSerializer;
		private IFormatSerializer xmlSerializer;

		public IFormatSerializer JsonSerializer
		{
			get
			{
				if (this.jsonSerializer == null)
				{
					this.jsonSerializer = new JsonSerializer();
				}

				return this.jsonSerializer;
			}
		}

		public IFormatSerializer JsonpSerializer
		{
			get
			{
				if (this.jsonpSerializer == null)
				{
					this.jsonpSerializer = new JsonSerializer();
				}

				return this.jsonpSerializer;
			}
		}

		public IFormatSerializer XmlSerializer
		{
			get
			{
				if (this.xmlSerializer == null)
				{
					this.xmlSerializer = new XmlSerializer();
				}

				return this.xmlSerializer;
			}
		}

		public IFormatSerializer GetSerializer(NameValueCollection headers, NameValueCollection queryString)
		{
			string callbackName = String.Empty;
			var mimeType = headers["Accept"]; // check content type too

			if (HttpContext.Current != null)
			{
				callbackName = queryString["jsonCallback"] ?? queryString["callback"];
			}

			if (mimeType.Contains(HttpConstants.MimeApplicationJson))
			{
				return String.IsNullOrEmpty(callbackName) ? this.JsonSerializer : this.JsonpSerializer;
			}

			if (mimeType.Contains("text/xml") || mimeType.Contains("application/xml"))
			{
				return this.XmlSerializer;
			}

			if (!String.IsNullOrEmpty(callbackName))
			{
				return this.JsonpSerializer;
			}

			return this.XmlSerializer;
		}
	}
}